package cn.pzhu.javaee.webapp.listener;

import java.beans.PropertyVetoException;
import java.sql.Connection;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.pzhu.javaee.webapp.config.WebAppConfig;
import cn.pzhu.javaee.webapp.context.WebAppContext;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * Application Lifecycle Listener implementation class InitListener
 *
 */
@WebListener
public class InitListener implements ServletContextListener {
	private Logger log=LoggerFactory.getLogger(InitListener.class);
    /**
     * Default constructor. 
     */
    public InitListener() {
        log.info("Init Listener Create");
    }

	/**
     * @see ServletContextListener#contextDestroyed(ServletContextEvent)
     */
    public void contextDestroyed(ServletContextEvent arg0)  { 
    	log.info("Init Listener Destroy");
    }

	/**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent sce)  { 
         log.info("---------Web App Context--------Init----------");
         WebAppContext appContext=WebAppContext.getWebAppContext();
         appContext.regsiter(sce.getServletContext());
        
         DataSource ds=createDataSource();
         appContext.setDataSource(ds);          
       
         String basePath=sce.getServletContext().getContextPath();
         log.info("Web App BasePath:"+basePath);
         appContext.setBasePath(basePath);
    }
    
    private DataSource createDataSource(){
    	log.info("create dataSource...");
    	String url=WebAppConfig.getDBUrl();
    	String user=WebAppConfig.getDBUser();
    	String password=WebAppConfig.getDBPassword();
    	log.debug("url:{}",url);
    	log.debug("user:{}",user);
    	log.debug("password:{}",password);
    	 
    	try {
    		ComboPooledDataSource ds=new ComboPooledDataSource();
        	ds.setUser(user);       
        	ds.setPassword(password);       
        	ds.setJdbcUrl(url);
			ds.setDriverClass("com.mysql.jdbc.Driver");
			ds.setInitialPoolSize(2); 
	    	ds.setMinPoolSize(1); 
	    	ds.setMaxPoolSize(10); 
	    	ds.setMaxStatements(50); 
	    	ds.setMaxIdleTime(60);
	    	
	    	Connection conn=ds.getConnection();
	    	if(conn!=null){
	    		log.info("Connection Pools test OK "+conn);
	    		conn.close();
	    	}
	    	return ds;
	    	
		} catch (Exception e) {			
			e.printStackTrace();
			log.error("create dataSource erro");
		}
    		return null;
    	
    }
    
    
	
}
